為了讓元素能夠適應各種顯示設備和螢幕尺寸, Flex Layout 的作用是讓 container 能夠使其 item 的 width/height (寬度/高度) 和 order (順序) 最佳利用/填滿可用的空間。 Flex container 讓 items 擴展以利用尚有的可用空間或使 items 縮小避免 layout overflow。

flex container, 裡面的項目自動成為 items 。main axis (主軸) 分隔 container 內的 itemcross axis (橫軸) 分隔 container 內的 item在某些情況下,你需要將 flex 屬性添加到 flex items 而不是 flex container
grow (增長) → items 應該佔用 container 內的可用空間量HTML
<ul class="flex-container">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
<li class="flex-item">6</li>
</ul>
CSS
.flex-container {
/* create a flex layout context */
display: flex | inline-flex;
/* indicate the flow direction
and let the items to wrap
* flex-direction: row;
* flex-wrap: wrap;
*/
flex-flow: row wrap; /* shorthand */
/* indicate how items are distributed in the remaining space */
justify-content: space-around;
padding: 0;
margin: 0;
list-style: none;
}
.flex-item {
background: blueviolet;
padding: 5px;
width: 200px;
height: 150px;
margin-top: 10px;
line-height: 150px;
color: #e0e0e0;
font-weight: bold;
font-size: 5em;
text-align: center;
}
Demo: https://codepen.io/ariel0122/pen/ZEoJZyV
卡片 container 使用 div 表示, 有 4 個圖像, 每個圖像代表一個數字。 這張卡片應該是 500px 寬和 200px 高, 具有 0.5em 寬的實心, #698733 邊框和 1em 的邊框半徑。卡片中的四個圖像應佔卡片高度的 70%, 垂直居中,水平空間平均分布。
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Number Card Demo</title>
<link rel="stylesheet" href="number.css">
</head>
<body>
<div>
<img src="number-0.png" alt="Number 0 tile" />
<img src="number-1.png" alt="Number 1 tile" />
<img src="number-2.png" alt="Number 2 tile" />
<img src="number-3.png" alt="Number 3 tile" />
</div>
</body>
</html>
CSS
div {
display: flex;
height: 200px;
width: 500px;
border: solid #698733 0.5em;
border-radius: 1em;
align-items: center;
justify-content: space-evenly;
}
div img {
height: 70%;
}

最後跟大家分享一個好用且有趣的網站, 可以拿來玩玩, 查看 Flex 屬性的視覺化輔助學習工具:
https://bychao.com/weird-flex/ (有支援多語系喔!英文/中文)